package com.lagou.edu.controller;

import com.lagou.edu.dao.ResumeDao;
import com.lagou.edu.pojo.Resume;
import com.lagou.edu.util.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Optional;

/**
 * 用户的操作控制类
 */
@RequestMapping("/demo")
@Controller
public class DemoController {

    private static final String LOGIN_COOKIE = "login_cook";

    @Autowired
    private ResumeDao resumeDao;

    @RequestMapping("/login")
    public String login(HttpServletRequest request, HttpServletResponse response,ModelMap modelMap){
        CookieUtil.delCookie(request,response);
        String error = request.getParameter("error");
        modelMap.put("error",error);
        return "/login";
    }


    @RequestMapping("/signup")
    public String signup(HttpServletRequest request,HttpServletResponse response,ModelMap modelMap){
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        if(!"admin".equals(username) || !"admin".equals(password)){
            modelMap.put("error","username error or passowrd error!");
            return "/login";
        }
        CookieUtil.addCookie(response,LOGIN_COOKIE,"1",3600);
        List<Resume> list = resumeDao.findAll();
        modelMap.put("list",list);
        return "/list";
    }

    @RequestMapping("/list")
    public String list(HttpServletRequest request,HttpServletResponse response,ModelMap modelMap){
        List<Resume> list = resumeDao.findAll();
        modelMap.put("list",list);
        return "/list";
    }


    @RequestMapping("/add")
    public String add(){
        return "/add";
    }

    @RequestMapping("/save")
    public String save(Resume resume){
        resumeDao.save(resume);
        return "redirect:/demo/list";
    }

    @RequestMapping("/edit")
    public String edit(HttpServletRequest request,ModelMap modelMap){
        String id = request.getParameter("id");
        Resume resume = new Resume();
        resume.setId(Long.parseLong(id));
        Example<Resume> example = Example.of(resume);
        Optional<Resume> one = resumeDao.findOne(example);
        System.out.println(one.get());
        modelMap.put("resume",one.get());
        return "/edit";
    }

    @RequestMapping("/update")
    public String update(Resume resume){
        resumeDao.save(resume);
        return "redirect:/demo/list";
    }


    @RequestMapping("/del")
    public String del(HttpServletRequest request){
        String id = request.getParameter("id");
        resumeDao.deleteById(Long.parseLong(id));
        return "redirect:/demo/list";
    }

}
